package com.yami.shop.bean.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yami.shop.bean.app.dto.FaceDesignConfigDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * FaceDesignConfigDto MyBatis类型处理器
 * 用于处理FaceDesignConfigDto对象与数据库JSON字符串之间的转换
 * @author AI Assistant
 */
@Slf4j
@MappedTypes(FaceDesignConfigDto.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class FaceDesignConfigTypeHandler extends BaseTypeHandler<FaceDesignConfigDto> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, FaceDesignConfigDto parameter, JdbcType jdbcType) throws SQLException {
        try {
            String json = objectMapper.writeValueAsString(parameter);
            ps.setString(i, json);
        } catch (JsonProcessingException e) {
            log.error("FaceDesignConfigDto序列化失败: {}", e.getMessage(), e);
            ps.setString(i, null);
        }
    }

    @Override
    public FaceDesignConfigDto getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return parseJson(json);
    }

    @Override
    public FaceDesignConfigDto getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return parseJson(json);
    }

    @Override
    public FaceDesignConfigDto getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return parseJson(json);
    }

    private FaceDesignConfigDto parseJson(String json) {
        if (json == null || json.trim().isEmpty()) {
            return null;
        }
        
        try {
            return objectMapper.readValue(json, FaceDesignConfigDto.class);
        } catch (JsonProcessingException e) {
            log.error("FaceDesignConfigDto反序列化失败: {}, JSON: {}", e.getMessage(), json, e);
            return null;
        }
    }
}